package com.dwin.h5.app.ui.system;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dwin.h5.app.R;
import com.dwin.h5.app.h5.X5WebView;
import com.dwin.h5.app.models.TabItem;
import com.dwin.h5.app.models.response.HomeTabRsp;
import com.dwin.h5.app.ui.BaseH5Activity;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.LocalManageUtil;
import com.dwin.h5.app.utils.NotificationsUtils;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.utils.http.UserManageRetrofit;
import com.dwin.h5.app.views.dialogs.NetLoadingDialog;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.litepal.LitePal;

import java.util.ArrayList;

import retrofit2.Response;

/**
 * 混合开发：登录页面
 */
public class LoginActivity extends BaseH5Activity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private RelativeLayout rl_loading, rl_error;
    private boolean h5HasError = false; // h5页面异常，标识位

    private String loginUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_h5);

        ImageView iv_loading = findViewById(R.id.iv_loading);
        iv_loading.setBackgroundResource(R.drawable.anim_loading_h5);
        AnimationDrawable ad = (AnimationDrawable) iv_loading.getBackground();
        ad.start();
        rl_loading = findView(R.id.rl_loading);
        rl_loading.setVisibility(View.VISIBLE);
        rl_error = findView(R.id.rl_error);
        rl_error.setOnClickListener(this);
        mWebView = findViewById(R.id.web_view);
        loginUrl = logMessage.getString("loginUrl", null);
        if (loginUrl != null) {
            webViewLoad(loginUrl);
        } else { // 重新请求网络
            getTabsInfo();
        }
    }

    // 加载显示WebView页面的UI
    private void webViewLoad(String loginUrl) {
        mWebView.loadUrl(loginUrl);
        Log.d(TAG, "page progress is :0 ");
        mWebView.setOnWebViewListener(new X5WebView.OnWebViewListener() {
            @Override
            public void onProgressChanged(WebView webView, int progress) {
                Log.d(TAG, "page progress is : " + progress);
                if (progress == 100) {
                    rl_loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onReceiveTitle(String title) {
                Log.d(TAG, "onReceiveTitle : " + title);
            }
        });
        // 页面加载错误时执行的方法，但是在6.0以下，有时候会不执行这个方法
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                h5HasError = true;
                rl_error.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                Log.d(TAG, "onPageFinished 0000");
                if (!h5HasError) {
                    rl_error.setVisibility(View.GONE);
                    rl_loading.setVisibility(View.GONE);
                }
                // 判断是否小推送。
                if (Constants.IS_HBDC3D) {
                    getNotification();
                }
            }
        });
    }

    // 获取通知权限
    private void getNotification() {
        if (!NotificationsUtils.isNotificationEnabled(this)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setCancelable(true)
                    .setTitle(R.string.note_no_permission)
                    .setMessage(R.string.note_no_permission02)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setPositiveButton(R.string.note_to_open, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("app_package", getPackageName());
                                intent.putExtra("app_uid", getApplicationInfo().uid);
                            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                            } else if (Build.VERSION.SDK_INT >= 15) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                            }
                            startActivity(intent);
                        }
                    });
            builder.setCancelable(false);
            builder.create().show();
        }
    }


    // 获取主页tab信息
    private void getTabsInfo() {
        NetLoadingDialog.showprogress(mContext, true);
        String language = LocalManageUtil.getSystemLocaleLng(mContext);
        UserManageRetrofit.getInstance().getHomeTabs(language, new retrofit2.Callback<HomeTabRsp>() {
            @Override
            public void onResponse(retrofit2.Call<HomeTabRsp> call, Response<HomeTabRsp> response) {
                if (Constants.HTTP_OK == response.body().code) {
                    logMessage.edit().putString("loginUrl", response.body().data.login_url);
                    logMessage.edit().putString("version", response.body().data.version);
                    ArrayList<TabItem> tabs = response.body().data.tabs;
                    LitePal.deleteAll(TabItem.class);
                    LitePal.saveAll(tabs);
                    loginUrl = response.body().data.login_url;
                    webViewLoad(response.body().data.login_url); // 刷新WebView
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(retrofit2.Call<HomeTabRsp> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getStackTrace());
                ToastUtil.toastLong(mContext, R.string.net_error);
                NetLoadingDialog.dismissprogress();
                rl_loading.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_error: // 刷新WebView 的UI
                rl_loading.setVisibility(View.VISIBLE);
                rl_error.setVisibility(View.GONE);
                mWebView.reload();
                break;
        }
    }

    private long firstClickBackTime = 0; // 第一次点击back键的时间

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                String url = mWebView.getUrl(); // h5页面，当前的url
                if (loginUrl != null && !loginUrl.equals(url)) {
                    mWebView.goBack();
                    return true;
                }
            }
            if (secondTime - firstClickBackTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(this, R.string.press_again_2exit, Toast.LENGTH_SHORT).show();
                firstClickBackTime = System.currentTimeMillis();
            }
        }
        return false;
    }

}
